<template>
	<view id="moments">
		<view style="height: 500upx;position: relative;">
			<image :src="bagavatar || '../../static/img/q.jpg'" @tap="showModal" data-target="RadioModal" class="home-pic">
			<view class="home-pic-base">
				<view class="top-pic">
					<image class="header" :src="userinfo.avatar || '../../static/img/toxiang.png'"></image>
				</view>
				<view class="top-name">{{userinfo.nickname}}</view>
			</view>
		</view>
		<view v-if="posts.length == 0" class="tishi">
			<image class="tiimg" src="../../static/img/zanwu.png">
			<view>空空如也</view>
		</view>
		<view v-else class="moments__post" @click.stop="blursend" v-for="(post,index) in posts" :key="index" :id="'post-'+index">
			<view class="post-left" @click="topuser(post.user_id, post.userinfo.nickname)">
				<image class="post_header" :src="post.userinfo.avatar != ''?post.userinfo.avatar:'../../static/image/bg_img.png'"></image>
			</view>

			<view class="post_right">
				<view style="display: flex;justify-content: space-between;">
					<view class="post-username">{{post.userinfo.nickname || '游客'}}</view>
					<image class="dete" @tap.stop="deleteitem(post.id, index)" v-if="userinfo.id == post.user_id" src="../../static/img/dele.png"></image>
				</view>	
				<view id="paragraph" class="paragraph">{{post.content}}</view>
				<!-- 相册 -->
				<view class="thumbnails">
					<view :class="post.images.length === 1?'my-gallery':'thumbnail'" v-for="(image, index_images) in post.images" :key="index_images">
						<image class="gallery_img" lazy-load mode="aspectFill" :src="image" :data-src="image" @tap="previewImage(post.images, index_images)"></image>
					</view>
				</view>
				<!-- 资料条 -->
				<view class="toolbar">
					<view class="timestamp">{{post.createtime}}</view>
					<view class="like" @tap.stop="like(index)">
						<image :src="post.is_zan===2?'../../static/img/islike.png':'../../static/img/like.png'"></image>
						<text class="con_d">点赞</text>
					</view>
					<view class="comment" @tap.stop="comment(index)">
						<image src="../../static/img/comment.png"></image>
						<text class="con_d">评论</text>
					</view>
				</view>
				<!-- 赞／评论区 -->
				<view class="post-footer">
					<view class="footer_content">
						<image class="liked" src="../../static/img/likeed.png"></image>
						<text class="nickname" v-for="(user,index_like) in post.praise" :key="index_like">{{user}},</text>
					</view>
					<view class="footer_content" v-for="(comment,comment_index) in post.comments" :key="comment_index" @tap.stop="reply(index,comment_index)">
						<text class="comment-nickname">{{comment.nickname}}:<text class="comment-content">{{comment.content}}</text></text>
					</view>
				</view>
			</view>
			<!-- 结束 post -->
		</view>

		<view class="foot" v-show="showInput">
			<!-- <chat-input @send-message="send_comment" @blur="blur" :focus="focus" :placeholder="input_placeholder"></chat-input> -->
			<view class="footer">
				<view class="footer-center">
					<input class="input-text" type="text" @confirm="send_comment" v-model="inputValue"  :focus="focus"  ></input>
				</view>
				<view class="footer-rights">
					<view id='msg-type' class="send-comment" @click.stop="send_comment">发送</view>
				</view>
			</view>	
		</view>
		<view class="uni-loadmore" v-if="showLoadMore">{{loadMoreText}}</view>
		<view class="cu-modal" :class="modalName=='RadioModal'?'show':''" @tap="hideModal">
			<view class="cu-dialog" @tap.stop="upbaimg">
				更换背景图
			</view>
		</view>
	</view>

</template>

<script>
	// import chatInput from '../../components/im-chat/chatinput.vue'; //input框
	import {mapState, mapActions} from 'vuex'
	export default {
		components: {
			// chatInput
		},
		data() {
			return { 
				modalName: null,
				userinfo: '',
				bagavatar:'', //背景图
				posts: '',//模拟数据
				index: '', //post索引
				comment_index: '', //评论索引
				input_placeholder: '评论', //占位内容
				focus: false, //是否自动聚焦输入框
				is_reply: false, //回复还是评论
				showInput: false, //评论输入框
				screenHeight: '', //屏幕高度(系统)
				platform: '',
				windowHeight: '' ,//可用窗口高度(不计入软键盘)
				loadMoreText: "加载中...",
				showLoadMore: false,
				lisize: 0, //本次加载数量
				page: 1,
				inputValue: '',
				limit: 15
			}
		},
		
		computed: {
			...mapState({
				opts: 'opts'
			})
		},
		onLoad() {
			this.userinfo = uni.getStorageSync('userinfo')
			if(this.userinfo.avatar){
				this.userinfo.avatar = this.$common.baseUrl + this.userinfo.avatar;
			}
			uni.getSystemInfo({ //获取设备信息
				success: (res) => {
					this.screenHeight = res.screenHeight; // 屏幕高度
					this.platform = res.platform; //获取系统平台
				}
			});
			uni.showLoading({
				mask: false
			});
			//初始化数据
			this.initData();
			//背景图
			this.initimage();
		},
		onShow() {
			this.$msgchat.initwork();
			uni.onWindowResize((res) => { //监听窗口尺寸变化,窗口尺寸不包括底部导航栏
				if(this.platform === 'ios'){
					this.windowHeight = res.size.windowHeight;
					this.adjust();
				}else{
					if (this.screenHeight - res.size.windowHeight > 60 && this.windowHeight <= res.size.windowHeight) {
						this.windowHeight = res.size.windowHeight;
						this.adjust();
					}
				}
			});
		},
		onHide() {
			uni.offWindowResize(); //取消监听窗口尺寸变化
		},
		onUnload() {
			this.max = 0,
				this.data = [],
				this.loadMoreText = "加载更多",
				this.showLoadMore = false;
		},
		onReachBottom() { //监听上拉触底事件
			this.showLoadMore = true;
			setTimeout(() => {
				//获取数据
				if (this.lisize == 15){//
					this.page++;
					this.initData();
				}else{
					this.loadMoreText = "暂无更多";
				}
			}, 1000);
		},
		onPullDownRefresh() { //监听下拉刷新动作
			this.page = 1;
			this.posts = '';
			this.initData();
			setTimeout(function() {
				//初始化数据
				uni.stopPullDownRefresh(); //停止下拉刷新
			}, 1000);
		},
		onNavigationBarButtonTap(e) {//监听标题栏点击事件
			if (e.index == 0) {
				this.navigateTo('./publish/publish')
			}
		},
		computed:{
			
		},
		methods: {
			...mapActions(['inituser']),
			navigateTo(url) {
				uni.navigateTo({
					url: url
				});
			},
			//好友详情
			topuser(uid, nickname){
				uni.navigateTo({
					url: '/pages/detailsData/detailsData?friend_id=' + uid
				})
			},
			//初始化背景图
			initimage(){
			   this.$common.requests('/api/circle_face/getimage').then(res =>{
				   if(res.data.code == 1){
					   if(res.data!= null){
						   this.bagavatar = this.$common.baseUrl + res.data.data.circle_image
					   }
				   }else{
					   this.$api.msg(res.data.msg)
				   }
			   })
			},
			//上传图片
			upbaimg(){
				let that = this;
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					// sourceType: ['album'],
					success: chooseImageRes => {
						that.tempFilePaths = chooseImageRes.tempFilePaths;
						uni.uploadFile({
							url: this.$common.baseUrl + '/api/common/upload', //上传接口地址
							filePath: that.tempFilePaths[0],
							name: 'file',
							enctype: 'multipart/form-data',
							formData: {
								mobile: that.phone
							},
							success: uploadFileRes => {
								let res = JSON.parse(uploadFileRes.data);
								// that.avatar = configs.baseUrl + res.data.url.substr(1);
								that.bagavatar = this.$common.baseUrl + res.data.url;
								that.editavatar(res.data.url);
								// that.alipayimg = that.baseurl + "/service" + res.data.alipayimg
								// this.$http.post('updateavatar',{avatar: res.data.url}).then(res => {
								// 	this.$api.msg(res.msg);
								// })
							}
						});
					}
				});
			},
			//更换背景图
			editavatar(avatar){
				var obj = {
					image: avatar
				}
				this.$common.requests('/api/circle_face/updateface', obj).then(res => {
					// console.log(res)
					if(res.data.code==1){
						this.$api.msg(res.data.msg);
						this.hideModal();
						return;
					}else{
						this.$api.msg(res.data.msg);
						return;
					}
					
				})
			},
			//初始化朋友圈数据
			initData(){
				var up = {
					page: this.page,
					limit: this.limit
				}
				this.$common.requests('/api/circle/circleIndex', up).then(res =>{
					this.showLoadMore = false;
					uni.hideLoading();
					if(res.data.code != 1){
						this.$api.msg(res.data.msg);
					}else{
						this.lisize = res.data.data.length;
						if(this.lisize ==0 ) return;
						res.data.data.forEach((item, index) => {
							// item.createtime = this.$common.timestampToTime(item.createtime);
							if(item.userinfo.avatar){
								item.userinfo.avatar = this.$common.baseUrl + item.userinfo.avatar;
							}
							 for(let i in item.images){
								 item.images[i] = this.$common.baseUrl + item.images[i];
							 }
						})
						this.posts = [...this.posts, ...res.data.data]
					}
				})
			},
			//初始化顶部信息
			// initTopdata(){
			// 	this.$common.requests('/api/circle/userinfo').then(res => {
					
			// 	})
			// },
			deleteitem(tid, index){
				let that = this;
				uni.showModal({
				    content: '确定要删除吗',
				    success: function (res) {
				        if (res.confirm) {
				           that.$common.requests('/api/circle/circledelete', {id: tid }).then(res =>{
				           	that.posts.splice(index, 1)
				           })
				        } else if (res.cancel) {
				        }
				    }
				});
				
			},
			//点赞or取消点赞
			like(index) {
				let up = {
					id: this.posts[index].id
				}
				let url = '';
				if(this.posts[index].is_zan == 2){
					url = '/api/circle_praise/dianzan'
				}else{
					url = '/api/Circle_praise/nozan'
				}
				this.$common.requests(url, up).then(res =>{
					if(res.data.code!= 1){
						this.$api.msg(res.data.msg);
					}else{
						if (this.posts[index].is_zan == 2) {
							this.posts[index].is_zan = 1;
							this.posts[index].praise.push(this.userinfo.nickname);
						} else {
							this.posts[index].is_zan = 2;
							this.posts[index].praise.splice(this.posts[index].praise.indexOf(this.userinfo.nickname), 1);
						}
						
					}
				})
			},
			blursend(){
				this.showInput = false;
			},
			//调取input
			comment(index) {
				this.showInput = true; //调起input框
				this.focus = true;
				this.index = index; //记录该数据下标
			},
			adjust() { //当弹出软键盘发生评论动作时,调整页面位置pageScrollTo
				return;
				uni.createSelectorQuery().selectViewport().scrollOffset(res => {
					var scrollTop = res.scrollTop;
					let view = uni.createSelectorQuery().select("#post-" + this.index);
					view.boundingClientRect(data => {
						uni.pageScrollTo({
							scrollTop: scrollTop - (this.windowHeight - (data.height + data.top + 45)), //一顿乱算
							// scrollTop: 50, 
							duration: 300
						});
					}).exec();
				}).exec();
			},
			reply(index, comment_index) {
				
				this.is_reply = true; //回复中
				this.showInput = true; //调起input框
				// let replyTo = this.posts[index].comments[comment_index].username;
				// this.input_placeholder = '回复' + replyTo;
				this.index = index; //post索引
				this.comment_index = comment_index; //评论索引
				this.focus = true;
			},
			//显示更换图
			showModal(e) {
				this.modalName = e.currentTarget.dataset.target
			},
			hideModal(e) {
				this.modalName = null
			},
			blur: function() {
				this.init_input();
			},
			//评论
			send_comment: function() {
				if (!this.inputValue) {
						uni.showModal({
							content:"还没有输入内容哦!",
							showCancel:false
						})
						return;
					}
				let comment_content = '';
				if (this.is_reply && this.posts[this.index].comments[this.comment_index].user_id != uni.getStorageSync('uid')) {
					var reply_username = this.posts[this.index].comments[this.comment_index].nickname;
					 comment_content = '回复' + reply_username + ':' + this.inputValue;
				} else {
					comment_content = this.inputValue;
				}
				let reply_id = '';
				if(this.is_reply){
					reply_id = this.posts[this.index].comments[this.comment_index].id;
				}
				let up = {
					circle_id: this.posts[this.index].id,
					reply_id: reply_id,
					content: this.inputValue
				}
				this.$common.requests('/api/circle_comments/commentadd', up).then(res =>{
					if(res.data.code == 1){
						if(this.is_reply){
							res.data.data.content = comment_content;
							res.data.data.nickname = this.userinfo.nickname;
						}else{
							res.data.data.nickname = this.userinfo.nickname;
						}
						this.posts[this.index].comments.push(res.data.data);
						this.inputValue = '';//清空上次输入的内容
						this.init_input();
						// this.initData();
					}
				})
			},
			init_input() {
				this.showInput = false;
				this.focus = false;
				this.input_placeholder = '评论';
				this.is_reply = false;
			},
			//图片预览
			previewImage(imageList, image_index) {
				var current = imageList[image_index];
				uni.previewImage({
					current: current,
					urls: imageList
				});
			},
			goPublish() {
				uni.navigateTo({
					url: './publish/publish',
					success: res => {},
					fail: () => {},
					complete: () => {}
				});
			}
		}
	}
</script>

<style scoped>
	@import url("../../common/friendCircle/index.css");
</style>
